package com.example.intelligenttransportation;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.intelligenttransportation.Utils.NetWorkInfo;
import com.example.intelligenttransportation.Utils.Recharge;
import com.example.intelligenttransportation.Utils.Users;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SuccessActivity extends AppCompatActivity {
    private Context context = SuccessActivity.this;
    private ListView listView;
    private Button set_ton ,sett_ton;
    private View longinDialogView;
    private List<Users> list = new ArrayList<>();
    private List<Integer> checkBoxIDList = new ArrayList<>();            //存储checkBox的值
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_success);
        listView=findViewById(R.id.a_list);
        sendRequestWithOkHttp();
        set_ton=findViewById(R.id.set);
        sett_ton=findViewById(R.id.settings);
        set_ton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(SuccessActivity.this,RechargeActivity.class));
            }
        });
        sett_ton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final StringBuilder list2 = new StringBuilder();
                final StringBuilder list1 = new StringBuilder();
                for (int i = 0; i <checkBoxIDList.size(); i++) {
                    list2.append("&"+list.get(0).getData().get(checkBoxIDList.get(i)).carno);
                    list1.append(list.get(0).getData().get(checkBoxIDList.get(i)).who);
                    Log.v("TAG","run:ooo"+list2);
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                LayoutInflater layoutInflater = LayoutInflater.from(context);
                final View longinDialogView= layoutInflater.inflate(R.layout.item_layout2, null);//找到定义的布局
                builder.setView(longinDialogView);//设置布局
                TextView text = longinDialogView.findViewById(R.id.re2_car);
                Button btn_1 = longinDialogView.findViewById(R.id.re2_qr);
                Button btn_2 = longinDialogView.findViewById(R.id.re2_qx);
                text.setText("车牌号:"+list2);
                builder.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
                final AlertDialog dialog = builder.create();  //创建对话框
                dialog.setCanceledOnTouchOutside(true); //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
                dialog.show();//展示Alert
                btn_1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        EditText edit = longinDialogView.findViewById(R.id.re2_many);//取到布局中的构件
                        String ste = edit.getText().toString().trim();
                        Log.i("TAG", "run:3333 "+ste);
//                        for (int i = 0; i <checkBoxIDList.size(); i++) {
//                            String car_no = list.get(0).getData().get(checkBoxIDList.get(i)).carno;
//                            String who = list.get(0).getData().get(checkBoxIDList.get(i)).who;
                        initData(list.get(0).getData().get(checkBoxIDList.get(0)).who,String.valueOf(list2),ste);
//                        }
                        dialog.dismiss();
                    }
                });
                btn_2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(context, "你点了取消", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });

            }
        });
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String s=  msg.obj.toString();
            Gson gson = new Gson();
            Users carList = gson.fromJson(s,Users.class);
            list.add(carList);
            listView.setAdapter(new MyAdapter(list));
        }
    };
    private void sendRequestWithOkHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient=new OkHttpClient();
                    Request request=new Request.Builder()
                            .url("http://hh1.me:5001/carlist")
                            .get()
                            .build();
                    Call call = okHttpClient.newCall(request);
                    Response response = call.execute();
                    assert response.body() != null;
                    String s = response.body().string();
                    Message msg= new Message();
                    msg.obj=s;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private  class MyAdapter extends BaseAdapter {
        List<Users> list_f ;

        public MyAdapter(List<Users> list1) {
            list_f=list1;

        }

        @Override
        public int getCount() {
            return list_f.get(0).getData().size();
        }

        @Override
        public Object getItem(int i) {
            return list_f.get(0).data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, final View v, ViewGroup viewGroup) {
            View view = View.inflate(SuccessActivity.this, R.layout.item_layout ,null);
            ImageView img=view.findViewById(R.id.i_img);
            TextView number=view.findViewById(R.id.i_i);
            TextView carNum=view.findViewById(R.id.i_car);
            TextView name=view.findViewById(R.id.use);
            final TextView balance=view.findViewById(R.id.many);
            final CheckBox checkBox = view.findViewById(R.id.i_c);
            Button button = view.findViewById(R.id.list_btn);
            final Users.DataBean users= list_f.get(0).getData().get(i);
            //获取复选框选中状态改变事件进行增删改
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    /** b=选中状态
                     * if b = true 将值添加至checkBoxIDList
                     * if b = false 将值从checkBoxIDList移除
                     * */
                    if (b) {
                        checkBoxIDList.add(i);
                        Log.v("TAG","sssss1"+checkBoxIDList);
                    }else {
                        checkBoxIDList.remove(new Integer(i));
                        Log.v("TAG","sssss2"+checkBoxIDList);
                    }
                }
            });
            number.setText(i+1+"");
            img.setImageResource(R.drawable.sh);
            carNum.setText(users.carno);
            name.setText("车主："+users.who);
            balance.setText("余额："+users.amount+"元");
            if(users.amount<10000){
                view.setBackgroundColor(Color.parseColor("#ffcc00"));
            }
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    chongzhi(users.carno,users.who);
                    final Runnable r =(new Runnable() {
                        @Override
                        public void run() {
                            TextView textView = longinDialogView.findViewById(R.id.wang);
                            int netWorkInfo = NetWorkInfo.getNetWorkInfo(SuccessActivity.this);
                            if (netWorkInfo==1) {
                                textView.setText(" wifi ");
                            }
                            if (netWorkInfo==-1) {
                                textView.setText("——");
                            }
                            if (netWorkInfo==0) {
                                textView.setText("3G/4G");
                            }handler.postDelayed(this,500);
                        }
                    });
                    handler.post(r);
                }
            });
            return view;
        }
    }
    private void chongzhi(final String carno , final String who) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        longinDialogView= layoutInflater.inflate(R.layout.recharge_layout, null);//找到定义的布局
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(longinDialogView);//设置布局
        final TextView text = longinDialogView.findViewById(R.id.re_car);
        text.setText("车牌号:"+carno);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {//设置监听内部类
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText edit = longinDialogView.findViewById(R.id.re_many);//取到布局中的构件
                String ste = edit.getText().toString().trim();
                initData(who,carno,ste);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(context, "你点了取消", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
        AlertDialog dialog = builder.create();  //创建对话框
        dialog.setCanceledOnTouchOutside(true); //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
        dialog.show();//展示Alert
    }
    private void initData(final String who, final String car_no, final String amount) {
        /*who: 充值人账户
        carno: 车牌号
        amount: 充值金额*/
        Log.i("TAG", "run:3333 "+who+car_no+amount);
        if(amount==""){
            Toast.makeText(context, "失败", Toast.LENGTH_SHORT).show();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient httpClient=new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
                String post = "{\"who\":\""+who+"\",\"carno\":\""+car_no+"\",\"amount\":\""+amount+"\"}";
                RequestBody requestBody = RequestBody.create(mediaType, post);
                //RequestBody requestBody = new FormBody.Builder().add("","");
                Request request=new Request.Builder()
                        .post(requestBody)
                        .url("http://hh1.me:5001/charge")
                        .build();
                Response response = null;
                try {
                    response = httpClient.newCall(request).execute();
                    final String string = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        OkHttpClient okHttpClient=new OkHttpClient();
                                        Request request=new Request.Builder()
                                                .url("http://hh1.me:5001/carlist")
                                                .get()
                                                .build();
                                        Call call = okHttpClient.newCall(request);
                                        Response response = call.execute();
                                        assert response.body() != null;
                                        final String s = response.body().string();
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Gson gson = new Gson();
                                                List<Users> list=new ArrayList<>();
                                                Users carList = gson.fromJson(s,Users.class);
                                                list.add(carList);
                                                listView.setAdapter(new MyAdapter(list));
                                                checkBoxIDList=new ArrayList<>();
                                            }
                                        });
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                            Toast.makeText(context, "成功&&刷新", Toast.LENGTH_SHORT).show();

                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
